package task;

import utils.DateUtils;

import java.sql.Time;
import java.util.concurrent.*;

public class TaskScheduler {
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); // 用于调度任务
    private final ExecutorService executor = Executors.newFixedThreadPool(10); // 用于执行任务，限制同时运行的任务数为10

    public TaskScheduler() {
    }

    public void startPeriodicTask(Runnable task, long period) {
        Runnable scheduledTask = () -> {
            Future<?> future = executor.submit(task); // 提交任务到executor执行
            // 无需显式控制future的取消或完成，由executor管理
        };

        // 使用定时器每period ms尝试执行任务
        scheduler.scheduleAtFixedRate(scheduledTask, 0, period, TimeUnit.MILLISECONDS);
    }


    // 应在适当的时候调用此方法关闭线程池
    public void shutdown() {
        scheduler.shutdown(); // 先关闭scheduler
        executor.shutdown(); // 再关闭executor

        try {
            if (!scheduler.awaitTermination(100, TimeUnit.MILLISECONDS)) {
                scheduler.shutdownNow(); // 如果等待时间后scheduler还未关闭，则强制关闭
            }
            if (!executor.awaitTermination(100, TimeUnit.MILLISECONDS)) {
                executor.shutdownNow(); // 如果等待时间后executor还未关闭，则强制关闭
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // 保留中断状态
            scheduler.shutdownNow(); // 中断所有任务
            executor.shutdownNow(); // 中断所有任务
        }
    }

    public static void main(String[] args) {
        TaskScheduler scheduler = new TaskScheduler();
        scheduler.startPeriodicTask(new Runnable() {
            @Override
            public void run() {
                System.out.println("Running task..." + DateUtils.getCurrentTimeFormatted("hh:mm:ss"));
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, 200);
    }
}
